<template>
	<div>
		<div class="cCard">
			<div class="rowStart">
				<image :src="getUserAvatarUrl" class="cImage"></image>
				<div style="margin-left:16px;flex:1;align-self: center;">
					<div style="font-weight: bold;margin-top: 4px;color: black;">{{getUserName}}</div>
				</div>
				<div v-if="!checkUserRegist" class="colCenter">
					<button type="warn" size="mini" @click="onJumpRegist">注册</button>
				</div>
			</div>
		</div>

		<uni-card title="待观看票" extra="全部订单" spacing="0px" padding="0px" :border="false">
			<template v-slot:title>
				<div class="rowBetween" style="line-height: 38px;">
					<div class="rowCenter">
						<div style="font-size: 16px;padding-left: 16px;font-weight: 400;color: #333333;">待观看票</div>
						<div class="colCenter" style="margin-left: 16px; font-size: 14px;padding-right: 16px;color: red;">
							<button @click="onShowPopup" type="warn" size="mini">客服咨询</button>
						</div>
					</div>
					<div style="font-size: 14px;padding-right: 16px;color: #2b6af9;" @click="jumpAllOrder">全部订单></div>
				</div>
			</template>
			<uni-list v-if="items !== undefined && items != null && items.length > 0" clickable>
				<uni-list-item :border="false" clickable v-for="(item,index) in items" @click="onJumpDetail(item)"
					:key="index">
					<template v-slot:body>
						<div class="rowStart" style="width: 100%;">
							<image :src="item.coverImg" style="width: 100px;height: 120px;border-radius: 8px;"
								mode="aspectFill">
							</image>
							<div style="margin-left: 16px;flex:1" class="colAround">
								<div style="font-size: 16px;font-weight: 500;color:#353535">{{item.productName}}
								</div>
								<div
									style="font-size: 16px;font-weight: 400;color: #333333;margin-bottom: 6px;margin-top: 10px;">
									{{item.theaterSession}}
								</div>
								<!-- <div style="color: #353535;">票价: <span
										style="font-size: 18px;font-weight: bold;color: #f04e7c;">￥
										{{item.theaterGrade}}</span>
								</div> -->
								
								<div class="rowBetween">
									<div style="color: #353535;">票价: <span style="font-size: 18px; font-weight: bold; color: #f04e7c;">￥{{item.theaterGrade}}</span></div>
									<div style="font-size: 14px; color:#999999;">数量: x{{item.tickerNum}}</div>
								</div>
							</div>
						</div>
					</template>
				</uni-list-item>
			</uni-list>
			<view v-else style="width: 100%;line-height: 60px;background-color: white;text-align: center;">暂无数据
			</view>
		</uni-card>

		<uni-card title="我的收益" v-if="checkIsChannel">
			<uni-grid :column="2" :highlight="true" :showBorder="false">
				<uni-grid-item>
					<view class="grid-item-box" @click="onJumpMoney(false)">
						<text class="textNum">￥{{moneyWait}}</text>
						<text class="text">待收益</text>
					</view>
				</uni-grid-item>
				<uni-grid-item>
					<view class="grid-item-box" @click="onJumpMoney(true)">
						<text class="textNum" style="color: #888888;">￥{{moneyDone}}</text>
						<text class="text">已收益</text>
					</view>
				</uni-grid-item>
			</uni-grid>
		</uni-card>
		
		<!-- 新增加微提示 -->
		<uni-popup ref="popup" :mask-click="false" type="center">
			<view class="colCenter marginTop marginBottom padding" style="background-color: #FFFFFF; border-radius: 10px; margin-left: 32px; margin-right: 32px;">
				<view class="colCenter marginLeft marginRight">
					<view class="rowCenter marginTop marginBottom">{{ wxTipInfo.fullText }}</view>
					<view class="rowBetween marginTop marginBottom">
						<button class="colCenter" style="width: 30%" type="default" @click="onClosePopup">关闭</button>
						<button class="colCenter" style="width: 60%;" type="warn" @click="onCopyWxCode">复制微信号</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</div>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from "vue";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import DbUtil from "@/utils/DbUtil";
	import StrUtil from "@/utils/StrUtils.js";
	import { gzhShare } from "@/utils/WxGzhUtil";
	import { useStore } from "vuex";
	
	const store = useStore();
	
	const userInfo = ref({});
	
	const sxf_theater = uniCloud.importObject("sxf-theater");
	
	// 加微提示信息
	const wxTipInfo = ref({
		tip1: "",
		wxCode: "",
		tip2: "",
		fullText: "",
		buttonName: "添加微信 咨询兑换实体票"
	})
	
	const popup = ref()
	
	onLoad(async(option) => {
		console.log("onLoad option", option);
		
		gzhShare({
			isShowMenu: false, // 隐藏菜单
			shareInfo: {}
		});
		
		// 获取加微提示信息
		const res = await sxf_theater.getWxTipText({});
		// console.log("-------res:", res);
		if (res.code == 0) {
			wxTipInfo.value = res.tipInfo;
			console.log("----wxTipInfo:", wxTipInfo.value);
		}
	});
	
	onShow(async(option) => {
		console.log("onShow:", option);
		userInfo.value = store.getters.getUserInfo;
		console.log("userInfo:", userInfo.value);
		if (StrUtil.isEmpty(userInfo.value) ||
		    StrUtil.isEmpty(userInfo.value.phone)) {
			// 未注册
			setTimeout(() => {
				uni.showModal({
					title: "注册提醒",
					content: "您还未注册，现在注册？",
					confirmText: "注册",
					success: (res) => {
						if (res.confirm) {
							onJumpRegist();
						}
					}
				});
			}, 500);
		} else {
			try {
				// 获取待观看的订单
				getItems();
				// 获取佣金
				getChannelMoney();
			} catch(ex) {
				console.error("onShow catch:", ex);
				// uni.hideLoading();
			}
		}
	});

	onMounted(async () => {
		console.log("onMounted");
		// // userInfo.value = getApp().globalData.curUserInfo;
		// userInfo.value = store.getters.getUserInfo;
		// console.log("=====", userInfo.value);
		
		// // 获取未结算的佣金收益
		// moneyWait.value = await getMoney(false);
		// // 获取已结算的佣金收益
		// moneyDone.value = await getMoney(true);
		// // 获取待观看的订单
		// items.value = await getItems();
	});
	
	const checkUserRegist = computed(() => {
		if (!StrUtil.isEmpty(userInfo.value) && 
		    !StrUtil.isEmpty(userInfo.value.phone)) {
			return true; // 已注册
		}
		return false;  // 未注册
	});
	
	const getUserAvatarUrl = computed(() => {
		if (!StrUtil.isEmpty(userInfo.value)) {
			return userInfo.value.avatarUrl;
		}
		return "";
	});
	
	const getUserName = computed(() => {
		if (!StrUtil.isEmpty(userInfo.value)) {
			return userInfo.value.userName;
		}
		return "";
	});
	
	const checkIsChannel = computed(() => {
		if (!StrUtil.isEmpty(userInfo.value) && 
			!StrUtil.isEmpty(userInfo.value.isChannel) && 
			userInfo.value.isChannel) {
			return true;
		}
		return false;
	});

	let moneyWait = ref(0);
	let moneyDone = ref(0);
	const getChannelMoney = async () => {
		try {
			if (!StrUtil.isEmpty(userInfo.value) && 
				!StrUtil.isEmpty(userInfo.value._id)) {
				const result = await DbUtil.getInstance("ndp-theater-channel-record").queryList({
					channelUserId: userInfo.value._id,
					isInvalid: false,
				});
				
				moneyWait.value = 0;
				moneyDone.value = 0;
				if (result !== undefined && result != null) {
					result.map((item) => {
						if (item.commissionAmount !== undefined && item.commissionAmount != null) {
							const amount = item.commissionAmount / 100;
							if (item.isSettle) {
								// 已结算
								moneyDone.value += amount;
							} else {
								// 未结算
								moneyWait.value += amount;
							}
						}
					});
				}
			}
		} catch(ex) {
			console.error("getMoney error:", ex);
			moneyWait.value = 0;
			moneyDone.value = 0;
		}
	};
	
	const getMoney = async (isSettle : boolean) => {
		try {
			if (!StrUtil.isEmpty(userInfo.value) && 
				!StrUtil.isEmpty(userInfo.value._id)) {
				const result = await DbUtil.getInstance("ndp-theater-channel-record").queryListWithDateTime({
					channelUserId: userInfo.value._id,
					isSettle: isSettle,
					isInvalid: false,
				}, "channelUserId", "sum(commissionAmount) as sum");

				if (result) {
					return Math.floor(result / 100);
				} else {
					return 0;
				}
			}
			return 0;
		} catch(ex) {
			console.error("getMoney error:", ex);
			return 0;
		}
	};
	
	const onJumpMoney = (value) => {
		uni.navigateTo({
			url: "/pages/my/ListShare?isSettle=" + value
		});
	};

	let items = ref(null);
	const getItems = async () => {
		console.log("getItems");
		try {
			console.log("getItems userInfo--->", userInfo.value);
			if (!StrUtil.isEmpty(userInfo.value) && 
				!StrUtil.isEmpty(userInfo.value._id)) {
				const res = await DbUtil.getInstance("ndp-theater-order").queryListWithDateTime({
					userId: userInfo.value._id,
					isInvalid: false,
					isDeleted: false,
				}, "theaterSessionTime");
				console.log("res:", res);
				items.value = res;
			} else {
				items.value =  [];
			}
		} catch(ex) {
			console.error("getItems error:", ex);
			items.value =  [];
		}
	};

	const onJumpDetail = (item : any) => {
		console.log("item===>", item);
		uni.navigateTo({
			url: "/pages/my/orderDetail?id=" + item._id
		});
	};
	
	const jumpAllOrder = ()=>{
		uni.navigateTo({
			url: "/pages/my/ListOrder"
		});
	};
	
	const onJumpRegist = () => {
		// 注册
		uni.navigateTo({
			url: "/pages/launch/regist"
		});
	};
	
	// 复制微信号
	const onCopyWxCode = () => {
		uni.setClipboardData({
			data: wxTipInfo.value.wxCode,
			success: (res) => {
				uni.showToast({
					title: "复制成功",
					icon: "success"
				});
			},
			fail: (err) => {
				uni.showToast({
					title: "复制失败",
					icon: "fail"
				});
			}
		});
	}
	
	const onShowPopup = () => {
		popup.value.open();
	}
	
	const onClosePopup = () => {
		popup.value.close();
	}
</script>

<style scoped lang="scss">
	.cImage {
		width: 58px;
		height: 58px;
		border-radius: 50%;
	}

	.cCard {
		padding: 16px 16px 0px 16px;
	}

	.grid-item-box {
		flex: 1;
		// position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}

	.textNum {
		font-size: 25px;
		color: #f04e7c;
		margin-bottom: 16px;
		font-weight: bold;
	}

	.text {
		font-size: 16px;
		color: #353535;
	}
</style>